using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text;
using Game.Global.Buffer;
using Game.Global.Helper;

namespace Game
{
    [RequireComponent(typeof(Editor_ObjData))]
    /// <summary>
    /// 自动关闭的场景物体组。
    /// <para>将在运行时将子物体们放入管辖物体中，距离Player较远时，将子物体们都disable掉</para>
    /// </summary>
    public sealed class SceneObjGroup : InteractiveGameObj
    {
        /// <summary>
        /// 存储Prefab对应的Buffer
        /// </summary>
        static Dictionary<GameObject, GameObjBuffer> g_objPrefabBuffer ;

        /// <summary>
        /// 存储GroupMgr中存储的可用的预制体（序号将与Mgr中的保持一致）
        /// </summary>
        static GameObject[] g_groupMgrObjPrefabs;

        /// <summary>
        /// 从Resources中读取资源的数据时的路径
        /// </summary>
        public const string C_DetailsPathInRes = "TerrainDetails";

        /// <summary>
        /// 在游戏运行中，是否有变动
        /// </summary>
        private bool m_isChangedInRuntime = false;

        /// <summary>
        /// This group is created or modified by user.
        /// </summary>
        private bool m_isReadFromUserData = false;
        
        [ContextMenuItem("Delete Serialized info", "Editor_DeleteSerializedInfo")]
        [ContextMenuItem("Assgin Serial Id", "Editor_ReAssignId")]
        /// <summary>
        /// 当前物体组的唯一ID
        /// </summary>
        [SerializeField] int m_groupObjIndex = -1;

        /// <summary>
        /// 用于控制的子物体，如果不赋值，会自动获取第一个子物体进行管理
        /// </summary>
        [SerializeField]GameObject m_objGroupToControll;

        /// <summary>
        /// <para>获得管理子物体的Transform</para>
        /// <para>Gets the manager of children objs</para>
        /// </summary>
        /// <value>The manage group object.</value>
        public GameObject ObjGroupManager
        {
            get
            {
                if (m_objGroupToControll == null)
                {
                    m_objGroupToControll = this.transform.GetChild(0).gameObject;
                }
                return m_objGroupToControll;
            }
        }

        protected override void Start()
        {
            base.Start();

            InitChildrenManager();

            //InitBuffers();
        }

        /// <summary>
        /// 初始化buffer
        /// </summary>
        public static void InitBuffers(GameObject[] prefabStoraged)
        {
            //由于现在Prefabs会是单例，所以如果初始化过，则不再初始化
            if(g_objPrefabBuffer!=null)
            {
                return;
            }

            g_objPrefabBuffer = new Dictionary<GameObject, GameObjBuffer>();


            //var prefabStoraged = GetPrefabStoraged();
            g_groupMgrObjPrefabs = prefabStoraged;

            GameObject prefabObj;
            //从配置中，获取此类Prefab应该使用的buffer长度（按名字取）
            var config = UConfig.GetConfig((typeof(SceneObjGroup).Name + "_BufferCfg"));

            for (int i = 0; i < prefabStoraged.Length; i++)
            {
                prefabObj = prefabStoraged[i];
                if(prefabObj!=null && g_objPrefabBuffer.ContainsKey(prefabObj)==false)
                {
                    var val = config.GetValue<int>(prefabObj.name);
#if UNITY_EDITOR
                    if(val==0)
                    {
                        val = 16;
                        Debug.Log("Default set ["+ prefabObj.name +"] buffer's size to "+val);
                        config.SetValue<int>(prefabObj.name, val);
                    }
#endif
                    g_objPrefabBuffer[prefabObj] = new GameObjBuffer(prefabObj, val);
                }
            }
        }

        private void InitChildrenManager()
        {
            if(m_transform.childCount> 1)
            {
                Debug.Log("Too many children attached. Maybe you should set them into one group");
            }
            ////--生成一个childrenManager作为代理者：
            //var childrenMgrObj = new GameObject(this.name + "_delegate");
            //m_childrenManager = childrenMgrObj.transform;

            ////--将子物体统统放入新的m_childrenManager中：

            //var children = m_transform.GetChilds();
            //for (int i = 0; i < children.Length; i++)
            //{
            //    children[i].transform.SetParent(m_childrenManager);
            //}
            ////代理物体返回到此物体的管理上：
            //m_childrenManager.SetParent(m_transform);
        }

        //---------------------------------------------------------------------------
        //              Public area
        //---------------------------------------------------------------------------
        #region Public area

        /// <summary>
        /// 自检Id
        /// </summary>
        public void CheckId()
        {
            if(m_groupObjIndex <0)
            {
                Debug.LogError(this.name + "has no id specified. You should delete it or set id for it.");
            }
        }

        /// <summary>
        /// 获得这个ObjGroup的唯一ID
        /// </summary>
        /// <returns></returns>
        public int GetObjGroupSerializedId()
        {
            if (m_groupObjIndex < 0)
            {
                //设置这个DataMgr的ID
                m_groupObjIndex = Editor_ObjHashIndexGenerator.GenerateIndex();
            }

            return m_groupObjIndex;
        }

        /// <summary>
        /// Set this group to Read From User Data
        /// </summary>
        public void SetReadWriteToUserData()
        {
            m_isReadFromUserData = true;
        }

        /// <summary>
        /// 标记此组的子物体有变动
        /// </summary>
        public void SetChangedInRuntime()
        {
            m_isChangedInRuntime = true;

            //设置即将写入用户目录：
            SetReadWriteToUserData();
        }

        /// <summary>
        /// 删除（将子物体归还buffer）物体
        /// </summary>
        /// <param name="obj">Object.</param>
        public void DeleteObj(GameObject obj)
        {
            //此部分是否需要
            var objPrefabs = GetPrefabStoraged();
            DeletePrefabObj(obj, objPrefabs);
        }

#if UNITY_EDITOR
        //TODO:与ObjDataMgr的关系需要重新整理，如果不是引用manager，而是manager反过来获取会很奇怪
        /// <summary>
        /// 在以posSrc为起点的位置，依照DataMgr提供的设定，批量生成对应的物体
        /// </summary>
        /// <param name="editorDataManager">提供设定，包括：生成起点及范围、生成数量、生成时参考的目标地形</param>
        public void Editor_BatchGenerateObjs(Editor_ObjData editorDataManager, SceneObjDataSetting objDataSetting)
        {
            GameObject objPrefab = objDataSetting.prefabObj;
            Vector3 posSrc = editorDataManager.transform.position;

            float rangeX = editorDataManager.batchGenerateRangeX;
            float rangeZ = editorDataManager.batchGenerateRangeZ;

            //--将位置偏移，因为生成函数是会将此点当做左下角的：
            posSrc.x -= rangeX * 0.5f;
            posSrc.z -= rangeZ * 0.5f;

            int randBatchCount = UnityEngine.Random.Range(editorDataManager.batch_generateCount_Min, editorDataManager.batch_generateCount_Max);

            //TD：后期如果需要在游戏中生成，则判断是否要传入Buffer进行Buffer的物体创建：
            GameObject[] gameObjects = TerrainHelper.GenerateDetailsOnTerrain(objPrefab, editorDataManager.batch_terrainTarget, randBatchCount, posSrc, rangeX, rangeZ);

            GameObject obj = null;
            for (int i = 0; i < gameObjects.Length; i++)
            {
                obj = gameObjects[i];
                SetNewObjAcordingToSetting(obj, editorDataManager.newObjParent.transform,objDataSetting);
            }
        }
#endif

        /// <summary>
        /// 创建一个物体后，按照dataMgr的设定的设置操作
        /// </summary>
        /// <param name="objParent">物体悬挂的父物体</param>
        /// <param name="go">新生成的物体</param>
        public void SetNewObjAcordingToSetting(GameObject go, Transform objParent,SceneObjDataSetting sceneObjDataSetting)
        {
            Transform goTransform = go.transform;
            Vector3 tmpPos = goTransform.position;
            //--位置偏移：
            tmpPos.y += sceneObjDataSetting.objDeltaPosY;
            //应用位置：
            goTransform.position = tmpPos;

            //随机转向：
            GameObjFunc.SetRandomRotation(goTransform, (RAND_ROTATE_DIRECTION)sceneObjDataSetting.randRotateDirection);

            //随机大小范围
            if (sceneObjDataSetting.changeScale)
            {
                GameObjFunc.SetRandomScale(goTransform, (float)sceneObjDataSetting.changeScaleMin, (float)sceneObjDataSetting.changeScaleMax);
            }


            //有设定更改父物体，则更改悬挂的父物体
            if (objParent != null)
            {
                goTransform.SetParent(objParent);
            }
            else
            {
                //否则放在本管理器内。
                goTransform.SetParent(objParent);
            }

            //新创建的物体，则设置其prefab信息来源：
            SetGOPrefabInfo(go, sceneObjDataSetting.prefabIndex);
#if UNITY_EDITOR
            //对于编辑器，注册可撤销创建：
            UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Create obj" );
#endif
        }

        /// <summary>
        /// 序列化子物体.
        /// </summary>
        public void SerializePrefabObjs()
        {
            var stringBuilder = new StringBuilder();

            GameObject[] childs = ObjGroupManager.transform.GetChilds();
            Transform currChildTrans;
            GameObject currGameObj;
            
            //GameObject currPrefabParent = null;
            int currPrefabIndex = -1;
            for (int i = 0; i < childs.Length; i++)
            {
                currGameObj = childs[i];

                //对于可能自己关闭（或归还了buff）的，跳过序列化：
                if(!currGameObj.activeInHierarchy)
                {
                    continue;
                }

                //对于运行时的序列化，只需要直接获取名字中带的prefabIndex信息即可
                currPrefabIndex = GetGOPrefabInfo(currGameObj);

                if (currPrefabIndex >= 0)
                {
                    currChildTrans = currGameObj.transform;

                    //--序列化信息
                    SerializeToStringBuilder(stringBuilder, currPrefabIndex, currChildTrans);

                }
            }

            if (stringBuilder.Length > 0)
            {
                //--返回的内容减1，以去掉末尾的结束符
                string fileContent = stringBuilder.ToString(0, stringBuilder.Length - 1);
                //--重新覆盖文件：
                if (m_isReadFromUserData)
                {
                    FileHelper.SaveFile(C_DetailsPathInRes, GetDataFileName(), fileContent);

                    Debug.Log("Serialized to " + FileHelper.GetWritablePath(C_DetailsPathInRes) + GetDataFileName());
                }
                else
                {
                    FileHelper.Editor_SaveResource(C_DetailsPathInRes, GetDataFileName(), fileContent);
                    Debug.Log("Serialized to " + FileHelper.GetResourcesPath(C_DetailsPathInRes) + GetDataFileName());
                }

            }
        }

        //========================================
        //                  Editor Area
        //========================================
#if UNITY_EDITOR
        /// <summary>
        /// 编辑器中拷贝时，需要重置ID
        /// </summary>
        public void Editor_ResetId()
        {
            this.m_groupObjIndex = -1;
        }

        /// <summary>
        /// 重新给这个物体分配ID
        /// </summary>
        public void Editor_ReAssignId()
        {
            if(this.m_groupObjIndex <0)
            {
                UnityEditor.Undo.RecordObject(this, "Set ID");
                //设置这个DataMgr的ID
                m_groupObjIndex = Editor_ObjHashIndexGenerator.GenerateIndex();
                Debug.Log("ID Assgined With:" + m_groupObjIndex);
            }
            else
            {
                Debug.Log("ID Allready exist.");
            }

        }

        [ContextMenu("Serialize info")]
        /// <summary>
        /// 【仅编辑器调用】将所有有Prefab链接的子物体都序列化为可存储的数据
        /// <para>返回内容：id，position，rotation，scale；</para>
        /// </summary>
        /// <returns></returns>
        public void Editor_SerializePrefabObjs()
        {
            //新建快照以记录obj的脚本信息（serialize过程中会被分配id，必须打快照才能记录：
            UnityEditor.Undo.RecordObject(this, "Set Obj info" + this.gameObject.name);
            SerializePrefabObjs();
        }

        [ContextMenu("Create Children from info")]
        /// <summary>
        /// 编辑器调用：从已经序列化的信息中创建游戏物体
        /// </summary>
        public void Editor_LoadObjsFromSerializedInfo()
        {
            CreatePrefabObjsFromSerializedStr(true);
        }

        [ContextMenu("Delete Children Objs")]
        /// <summary>
        /// Delete all serialized objects that under obj group.
        /// </summary>
        public void Editor_DeleteAllObjs()
        {
            DeleteAllPrefabObjs(true);
        }

        [ContextMenu("Delete Serialized Info")]
        /// <summary>
        /// 编辑器调用：删除已经序列化的信息类
        /// </summary>
        public void Editor_DeleteSerializedInfo()
        {
            if (!UnityEditor.EditorUtility.DisplayDialog("Confirm?", "Delete serialized info cannot be undo.", "Yes"))
            {
                return;
            }
            var path = FileHelper.GetResourcesPath(C_DetailsPathInRes);
            var fullPath = path + GetDataFileName() + ".txt";
            Editor_ResetId();
            if (FileHelper.DeleteFile(fullPath))
            {
                Debug.Log("Deleted serialized info: " + fullPath);
            }
            else
            {
                Debug.LogWarning("File not found at "+fullPath);
            }
        }

#endif


        #endregion

        //---------------------------------------------------------------------------
        //              Private area
        //---------------------------------------------------------------------------
        #region Private area

        protected override void OnWakeUp()
        {
            base.OnWakeUp();

            //读取文件，并从Buffer中创建对应的物体
            CreatePrefabObjsFromSerializedStr();

            ObjGroupManager.SetActive(true);
        }

        protected override void OnSleep()
        {
            base.OnSleep();

            //如果有子物体变更，则还需要存储一次子物体信息
            if(m_isChangedInRuntime)
            {
                SerializePrefabObjs();

                m_isChangedInRuntime = false;
            }

            //归还Obj到buffer中
            DeleteAllPrefabObjs();

            ObjGroupManager.SetActive(false);

            
        }

        /// <summary>
        /// 从序列化过的内容中，创建出对应的Prefabs
        /// </summary>
        private void CreatePrefabObjsFromSerializedStr(bool isEditor = false)
        {
            if(m_groupObjIndex<0)
            {
                Debug.LogError("No index given, so this will skip loading.");
                return;
            }
            //--获得文件内容：
            string fileContent = m_isReadFromUserData ?
                FileHelper.ReadFile(C_DetailsPathInRes,GetDataFileName())
                :FileHelper.LoadResource(C_DetailsPathInRes, GetDataFileName());
            
            if (string.IsNullOrEmpty(fileContent))
            {
                Debug.LogError("NO FILE CONTENT FOUND for " + this.gameObject + " with id: " + GetDataFileName());
                return;
            }

            //文件多个物体信息的分段：
            string[] infos = fileContent.Split(';');

            var prefabStoraged = GetPrefabStoraged();

            int prefabIndex;
            Vector3 pos, rotation, scale;
            string childSerializedInfo;
            GameObject prefabObj, currObj;
            for (int i = 0; i < infos.Length; i++)
            {
                //解析出对应的信息，并从buffer中创建物体：
                ParseGameObjInfoFrom(infos[i], out prefabIndex, out pos, out rotation, out scale,out childSerializedInfo);
                //Debug.Log("Parse info :" + prefabIndex + " " + pos + " " + rotation + " " + scale);
                prefabObj = prefabStoraged[prefabIndex];

#if UNITY_EDITOR
                //如果是编辑器行为，则直接调用编辑器工具创建并保持链接
                if (isEditor)
                {
                    currObj = (GameObject)UnityEditor.PrefabUtility.InstantiatePrefab(prefabObj);
                    UnityEditor.Undo.RegisterCreatedObjectUndo(currObj, "Deserialized obj");
                }
                else
#endif
                {
                    //非编辑器的情况下，则使用Buffer的方式生成物体：
                    var buffer = g_objPrefabBuffer[prefabObj];

                    currObj = buffer.PopObjectBuffered();
                }

                //--设定这个物体的Prefab 序列号信息
                SetGOPrefabInfo(currObj, prefabIndex);

                if(string.IsNullOrEmpty( childSerializedInfo)==false)
                {
                    //有序列化信息的情况下，尝试给数据：
                    var objSerializable = currObj.GetComponent<ISceneObjSerializable>();
                    if(objSerializable==null)
                    {
                        Debug.LogError("No " + typeof(ISceneObjSerializable).Name + " attached on obj "+currObj);
                    }
                    else
                    {
                        objSerializable.Deserialized(childSerializedInfo);
                    }
                }

                //--设定位置等信息
                var trans = currObj.transform;
                trans.position = pos;
                trans.rotation = Quaternion.Euler(rotation);
                trans.localScale = scale;
                trans.SetParent(ObjGroupManager.transform);

            }
        }

        /// <summary>
        /// 将创建出的Prefabs归还到buffer中
        /// </summary>
        /// <param name="editorDelete">是否是编辑器调用的删除，是的话，将立即删除而归还到buffer</param>
        private void DeleteAllPrefabObjs(bool editorDelete = false)
        {
            //获得obj对应的Prefab（子物体名字后缀即为Prefab在DataMgr中的位置id）
            var childObjs = ObjGroupManager.transform.GetChilds();

#if UNITY_EDITOR
            //编辑器模式，直接删除：
            if (editorDelete)
            {
                foreach (var obj in childObjs)
                {
                    UnityEditor.Undo.DestroyObjectImmediate(obj);
                }

                return;
            }
            else
#endif
            {
                //游戏中，则采用归还buffer
                var objBufferStoraged = GetPrefabStoraged();
                GameObject currObj;
                for (int i = 0; i < childObjs.Length; i++)
                {
                    currObj = childObjs[i];
                    DeletePrefabObj(currObj,objBufferStoraged);
                }
            }
        }

        private void DeletePrefabObj(GameObject obj,GameObject[] objPrefabs )
        {
            int prefabIndex = GetGOPrefabInfo(obj);
            //找到物体对应的当前存储的prefab源，再根据prefab找到全局的buffer，放回buffer：
            g_objPrefabBuffer[objPrefabs[prefabIndex]].PushObject(obj);
        }

        /// <summary>
        /// 从DataManager中获得其存储的Prefab
        /// </summary>
        /// <returns></returns>
        private GameObject[] GetPrefabStoraged()
        {
            if(g_groupMgrObjPrefabs!=null)
            {
                return g_groupMgrObjPrefabs;
            }
            else
            {
                if(Application.isPlaying)
                {
                    Debug.LogWarning("No g_groupMgrObjPrefabs Initialed.");
                }
            }

            var groupManager = m_transform.GetComponentInParent<SceneObjGroupManager>();
            if(groupManager==null)
            {
                Debug.LogError("You should set a " + typeof(SceneObjGroupManager).Name + " as parent.");
            }
            
            var prefabsStoraged = groupManager.GetAllGameObjPrefabs();

            return prefabsStoraged;
        }

        /// <summary>
        /// 获得Data存储的文件名
        /// </summary>
        /// <returns></returns>
        private string GetDataFileName()
        {
            return GetObjGroupSerializedId().ToString();
        }

        /// <summary>
        /// 将信息序列化为：
        /// id&amp;posX,posY,posZ&amp;rotation&amp;scale;
        /// <para>例如：1&amp;1,2,3&amp;0,0,0&amp;1,1,1;</para>
        /// </summary>
        /// <param name="stringBuilder">stringBuilder</param>
        /// <param name="prefabIndex">prefab在DataMgr中的序号</param>
        /// <param name="trans">Transform</param>
        private static void SerializeToStringBuilder(StringBuilder stringBuilder, int prefabIndex,Transform trans)
        {
            stringBuilder.Append(prefabIndex);
            stringBuilder.Append("&");
            VectorHelper.ToSerializedString( trans.position,stringBuilder);
            stringBuilder.Append('&');

            VectorHelper.ToSerializedString(trans.rotation.eulerAngles,stringBuilder);
            stringBuilder.Append('&');

            VectorHelper.ToSerializedString(trans.localScale,stringBuilder);


            //添加子物体的序列化信息：
            var objSerializable = trans.GetComponent<ISceneObjSerializable>();
            if (objSerializable != null)
            {
                //--获得生成的buffer：
                var bufferSrc = g_objPrefabBuffer[trans.gameObject];
                //追加信息：
                string childStr = objSerializable.Serialized(bufferSrc);

#if UNITY_EDITOR
                //编辑器模式时，会检查一下不能含有分号和&号：
                if(string.IsNullOrEmpty(childStr))
                {
                    Debug.LogWarning("Empty child obj info.");
                }
                else if(childStr.Contains(";") 
                    || childStr.Contains("&"))
                {
                    Debug.LogError("Could not contain ';' or '&");
                    return;
                }
#endif 

                stringBuilder.Append('&');
                stringBuilder.Append(childStr);
            }

            stringBuilder.Append(';');
        }

        /// <summary>
        /// 这个物体是否已经序列化过了
        /// </summary>
        /// <param name="currGameObj"></param>
        private bool IsGOHasPrefabInfo(GameObject currGameObj)
        {
            return currGameObj.name.Contains("#");
        }

        /// <summary>
        /// 设置这个游戏物体是序列化时用的prefab Id
        /// </summary>
        /// <param name="currGameObj"></param>
        /// <param name="prefabIndex"></param>
        private void SetGOPrefabInfo(GameObject currGameObj, int prefabIndex)
        {
            string preName = currGameObj.name;
            int index =  preName.LastIndexOf('#');
            if(index>=0)
            {
                preName = preName.Remove(index);
            }

            preName = preName + "#" + prefabIndex;
            currGameObj.name = preName;
        }

        /// <summary>
        /// 获得这个物体序列化信息中的Prefab Id（在此DataMgr中的id，而不是全局的）
        /// </summary>
        /// <returns>The GOS erialized info.</returns>
        /// <param name="obj">Object.</param>
        private int GetGOPrefabInfo(GameObject obj)
        {
            string objName = obj.name;
            string idPart = objName.Substring(objName.LastIndexOf('#')+1);
            int prefabId;
            if(!int.TryParse(idPart,out prefabId))
            {
                Debug.LogError("No prefab id found at " + objName+", subString:"+idPart);
                prefabId = -1;
            }

            return prefabId;
        }


        /// <summary>
        /// 从序列化的信息中，取出对应信息
        /// </summary>
        /// <param name="info"></param>
        /// <param name="prefabIndex"></param>
        /// <param name="pos"></param>
        /// <param name="rotation"></param>
        /// <param name="scale"></param>
        /// <param name="childSerializeInfo">子物体的序列化信息</param>
        private static void ParseGameObjInfoFrom(string info, out int prefabIndex, out Vector3 pos, out Vector3 rotation, out Vector3 scale,out string childSerializeInfo)
        {
            childSerializeInfo = null;
            
            string[] infoPart = info.Split('&');

            int.TryParse(infoPart[0], out prefabIndex);
            pos = VectorHelper. GetVector3FromString(infoPart[1]);
            rotation = VectorHelper.GetVector3FromString(infoPart[2]);
            scale = VectorHelper.GetVector3FromString(infoPart[3]);

            if(infoPart.Length>4)
            {
                childSerializeInfo = infoPart[4];
            }
            else
            {
                childSerializeInfo = null;
            }
        }



        [ExecuteInEditMode]
        [System.Serializable]
        private class Editor_ObjHashIndexGenerator
        {
            const string C_Folder = "IndexGenerator";
            const string C_FileName = "id";
            static int g_currIndex = -1;
            public static int GenerateIndex()
            {
                //读取id：
                if (g_currIndex < 0)
                {
                    //编辑器下读取Resources优先
#if UNITY_EDITOR
                    string str = FileHelper.LoadResource(C_Folder, C_FileName);
#else 
                    //运行时读取用户目录下的
                    string str = FileHelper.ReadFile(C_Folder, C_FileName);
#endif

                    if (string.IsNullOrEmpty(str))
                    {
#if UNITY_EDITOR
                        //编辑器模式下，则直接为0重新开始：
                        g_currIndex = 0;
#else
                        //发布时，反而要重新获取一次Resources中的内容，这样才能同步到序号
                        str = FileHelper.LoadResource(C_Folder, C_FileName);    
#endif
                    }

                    if (!int.TryParse(str, out g_currIndex))
                    {
                        Debug.LogError("Content ["+str+"]could not be parse from:"+ FileHelper.GetWritablePath(C_Folder));
                        Debug.LogError("ID will be reset to 0");
                    }
                }

                int result = g_currIndex;
                g_currIndex++;

                SaveIndex();
                return result;

            }


            public static void SaveIndex()
            {
#if UNITY_EDITOR
                Debug.Log("Save index to resource");
                //--对于调试时，需要放到资源区，这样发布的时候才能标注场景中的ObjGroup序号到哪里了：
                FileHelper.Editor_SaveResource(C_Folder, C_FileName, g_currIndex.ToString(),false);
#else
                Debug.Log("Save index to User Data");
                //--对于发布到的运行时，才能保存到用户目录中
                FileHelper.SaveFile(C_Folder, C_FileName, g_currIndex.ToString());
#endif
            }
        }
#endregion
    }
}